package com.cloud.controller;

import com.cloud.common.result.Result;
import com.cloud.common.result.ResultCode;
import com.cloud.model.entity.Payment;
import com.cloud.model.form.PaymentForm;

import lombok.RequiredArgsConstructor;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 订单表 前端控制器
 *
 * @author Sailer Wen
 * @since 2024-07-22
 */
@RestController
@RequestMapping("/orders")
//@RequiredArgsConstructor
public class OrderController {

   public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/create")
    public Result<Payment> create(@RequestBody PaymentForm formData) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment", formData, Result.class);
    }

    // getForObject 返回对象为响应体中数据转化成的对象,基本上可以理解为Json
    @GetMapping("/{id}")
    public Result<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, Result.class);
    }

    // getForEntity 返回对象为ResponseEntity对象，包含了响应中的一些重要信息，比如响应头、响应状态码、响应体等
    @GetMapping("/getForEntity/{id}")
    public Result<Payment> getPayment2(@PathVariable("id") Long id) {
        ResponseEntity<Result> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/" + id, Result.class);

        if(entity.getStatusCode().is2xxSuccessful()){
//            entity.getStatusCode()
//            entity.getHeaders()
            return entity.getBody();
        }else {
            return Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR,"操作失败");
        }
    }

}
